<?php
require_once 'Artdepot/Controller/Action.php';

class IndexController extends Artdepot_Controller_Action
{

    public function init()
    {
    	parent::init();
    }
    
    public function thanksAction(){
    	$code = $this->_request->getParam("code");
    	$orderId = (int) $this->_request->getParam("order");
    	
    	if(md5($orderId."HUIDALIAN") != $code){
    		$this->view->message = "Your order code is invalid!";
    		$this->_response->sendResponse();
    		exit();
    	}
    	
    	$table = New Model_DbTable_Order();
    	$theOrder = $table->fetchRow("id = $orderId");
    	
    	if ($theOrder){
    		$this->view->message = "Thank you! We will contact you by e-mail within 12 hours. ";
    		$this->sendPaiedEmail($theOrder);
    	}else{
    		$this->view->message = "Your order code is invalid!";
    		$this->_response->sendResponse();
    		exit();
    	}
    	
    }

    public function indexAction()
    {
    	
    	//当前展览
    	$exhibitionTable = new Model_DbTable_Exhibition();
    	$currentExhibition = $exhibitionTable->getCurrentExhibition();
    	
    	if ($currentExhibition){
    		$this->view->exhibition = $currentExhibition;
    	}
    	
		$artworkTable = new Model_DbTable_ArtWork();
		$artistTable = new Model_DbTable_Artist();
		$categoryTable = new Model_DbTable_ArtworkCategory();
		$cates = $categoryTable->fetchAll();
		$cateMap = array();
		foreach ($cates as $cate) {
			$cateMap[$cate->id] = $cate->name;
		}
		$artworks = $artworkTable->fetchAll("display_positions=1", array('display_order', 'id'), 18);
		
		//首页推荐新闻 1个
		$newsTable = new Model_DbTable_News();
		$recommandNews = $newsTable->fetchRow("display_position=1", array('display_order', 'id'));
		$this->view->recommandNews = $recommandNews;
		
		//首页右侧艺术家访谈 1个
		$artistTable = new Model_DbTable_Artist();
		$artistInterview = $artistTable->fetchRow("display_position=2");
		$this->view->artistInterview = $artistInterview;
		
		
		//首页右侧艺术家评分 3个
		$artistScores = $artistTable->fetchAll("display_position=1", 'id', 3);
		$this->view->artistScores = $artistScores;
		

		//首页批评家说 3个
		$artistForCriticise = $artistTable->fetchRow("display_position=3");
		$criticiseTable = new Model_DbTable_Criticise();
		$criticises = $criticiseTable->fetchAll("display_position=1 AND artist = $artistForCriticise->id", null, 3);
		$this->view->criticises = $criticises;
		$this->view->artistForCriticise = $artistForCriticise;
		
		//首页批评家说展示一个作家的代表作
		$typicalArtworks = $artistForCriticise->getTypicalArtworks(1);
		$this->view->typicalArtwork = $typicalArtworks->current();
		
		//首页销售趋势
		$trendsTable = new Model_DbTable_SalesTrends();
		$this->view->trends = $trendsTable->fetchAll(null, "order ASC");
		
		$this->view->artistMap = $artistTable->getMap();
		$this->view->categoryMap = $cateMap;
		$this->view->artworks = $artworks;
		
    }

    public function loginAction()
    {
    	$this->view->title = 'Sign in - ';
    	if ($this->_getParam('registered')) {
    		$this->view->message = 'Thanks for Signing Up!';
    		return;
    	}
    	if ($this->_getParam('email', '') && $this->_getParam('passwd', '')) {
			$adapter = new Zend_Auth_Adapter_DbTable ( Zend_Db_Table::getDefaultAdapter (), 'customer', 'email', 'passwd', 'MD5(?)' );
			$adapter->setIdentity ($this->_getParam('email', ''));
			$adapter->setCredential ($this->_getParam('passwd', ''));
			
			$result = $this->auth->authenticate ( $adapter );
			if ($result->isValid ()) {
				$theUser = $adapter->getResultRowObject(null, "passwd");
				$this->auth->getStorage()->write($theUser);
				$this->_redirect ( '/' );
				return;
			}
    	}
    	if ($this->_request->isPost()) {
			$this->view->message = 'Invalid email or password.';
    	}
    }
    
	public function logoutAction() {
		$this->auth->clearIdentity ();
		$this->_redirect('/');
	}
	
	public function advanceSerachAction(){
		
	}

    public function registerAction()
    {
    	$this->view->title = 'Sign up - ';
    	if ($this->_request->isPost()) {
    		$email = $this->_getParam('email', '');
    		$name = $this->_getParam('name', '');
    		$passwd = $this->_getParam('passwd', '');
    		$passwd2 = $this->_getParam('passwd2', '');
    		$emailValidator = new Zend_Validate_EmailAddress();
    		if (!$emailValidator->isValid($email)) {
    			$this->view->message = 'Invalid email address.';
    			return;
    		}
    		if (empty($name)) {
    			$this->view->message = 'Please enter your full name.';
    			return;
    		}
    		if (empty($passwd) || empty($passwd2)) {
    			$this->view->message = 'Please enter your password.';
    			return;
    		}
    		if ($passwd != $passwd2) {
    			$this->view->message = 'Password does not match.';
    			return;
    		}
    		$customerTable = new Model_DbTable_Customer();
    		$customer = $customerTable->fetchRow($customerTable->select()->where('email=?', $email));
    		if (!empty($customer)) {
    			$this->view->message = 'The email address already exists.';
    			return;
    		}
    		$customer = $customerTable->createRow();
    		$customer->email = $email;
    		$customer->name = $name;
    		$customer->passwd = md5($passwd);
    		$customer->register_on = date('Y-m-d H:i:s');
    		$id = $customer->save();
    		$this->_redirect('/index/login?registered=1');
    	}
    }
    
    public function sendPaiedEmail($order){
    	$salesEmail = "sales@artdepot.cn";
    	$emailTitle = "Notice, the order for artwork " . $order->getArtwork()->name . " has been paid.";
    	$emailContent = <<<EOF
    	Dear,
    		the order for artwork {$order->getArtwork()->name} has been paid, please confirm, here is the link to this order:
    		<a href="http://www.artdepot.cn/admin/edit-order/id/{$order->id}" target="_blank">http://www.artdepot.cn/admin/edit-order/id/{$order->id}</a>
EOF;
		$mail = new Zend_Mail();
		$mail->setBodyHtml($emailContent)
			->setSubject($emailTitle)
			->setFrom("admin@artdepot.cn", "system admin")
			->addTo($salesEmail)
			->send();
    }
    
    public function testEmailAction(){
    	$salesEmail = "sales@artdepot.cn";
    	$emailTitle = "Notice, the order for artwork xxx has been paid.";
    	$emailContent = <<<EOF
    	Dear,
    		the order for artwork xxx has been paid, please confirm, here is the link to this order:
    		<a href="http://www.artdepot.cn/admin/show-order/1" target="_blank">http://www.artdepot.cn/admin/show-order/1</a>
EOF;
		$mail = new Zend_Mail();
		$mail->setBodyHtml($emailContent)
			->setSubject($emailTitle)
			->setFrom("admin@artdepot.cn", "system admin")
			->addTo($salesEmail)
			->addTo("fidy.watcher@gmail.com")
			->addTo("1608688@qq.com")
			->send();
			exit();
    }
    
    public function testSizeAction(){
    	Zend_Layout::getMvcInstance()->disableLayout();
    	$table = new Model_DbTable_ArtWork();
    	$artworks = $table->fetchAll();
    	
    	$this->view->total = $artworks->count();
    	$this->view->artworks = array();
    	$i = 0;
    	foreach ($artworks as $artwork){
    		$artwork->size = strtolower( str_replace("*", "x", str_replace("×", "x", trim($artwork->size))) );
    		if ($artwork->size != ""){
    			$this->view->artworks[$i]["orig"] = $artwork->size;
    			$matches = array();
    			if(preg_match('/^(\d+(?:\.\d)?)\s*cm\s*x\s*(\d+(?:\.\d)?)\s*cm(?:\s*x\s*(\d+(?:\.\d)?)(?:\s*cm))?$/', $artwork->size, $matches)){
					$this->view->artworks[$i]["matches"] = $matches;
					$newValue = $matches[1] . " x " . $matches[2] . ($matches[3] ? (" x " .$matches[3] . " cm") : " cm");
					$inchValue = round($matches[1] * 0.3937, 1) . " x " . round($matches[2] * 0.3937, 1) 
										. ($matches[3] ? (" x " .round($matches[3] * 0.3937, 1) . " in") : " in");
					
					$artwork->size = $newValue;
					$artwork->inch_size = $inchValue;
					$artwork->save();
					
					$this->view->artworks[$i]["new"] = $newValue;
					$this->view->artworks[$i]["inch"] = $inchValue;
    			}
    		}
    		$i++;
    	}
    	
    	
    }
    


}





















